package com.example.yunxinagyue

import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.io.*

class Music(var num:String,var musicName:String,var play:String,var album:String)
class Info(var count:Int):Serializable
var info_obj=Info(0)

class MusicPlayList : AppCompatActivity(), MusicListAdapter.OnItemClickListener {

    private val musicList=ArrayList<Music>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_music_play_list)
        val musicList = findViewById<RecyclerView>(R.id.music_list)

        info_obj = loadData() ?: Info(0)
        Logger.info(TAG, "info_obj.count = ${info_obj.count}")
        getMusic()
        initialMusic()
        val layoutManager = LinearLayoutManager(this)
        musicList.layoutManager = layoutManager
        val adapter = MusicListAdapter(this.musicList)
        musicList.adapter = adapter
        supportActionBar?.hide()

        adapter.setOnItemClickListener(this)


    }

    private fun initialMusic(){
        for(i in 1 until musicNameList.size){
            if((i+5)<= musicNameList.size-1){
                musicList.add(Music("$i",
                    musicNameList[(i+5)], musicSingerList[i+5], musicAlbumList[i+5]
                ))
            }else{
                break
            }
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            android.R.id.home -> finish()
        }
        return super.onOptionsItemSelected(item)
    }

    private fun getMusic() {
        val cursor=contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,null,null,null,null)
        cursor?.apply {
            while(moveToNext()) {
                val musicPath=getString(getColumnIndexOrThrow(MediaStore.Audio.Media.DATA))
                val musicName=getString(getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE))
                val musicSinger=getString(getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST))
                val musicAlbum=getString(getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM))
                Logger.info(TAG, "get Music Path = $musicPath, $musicName")
                musicNameList.add(musicName)
                musicSingerList.add(musicSinger)
                musicAlbumList.add(musicAlbum)
                musicPathList.add(musicPath)
            }
            info_obj.count++
            close()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        saveData()
    }
    private fun saveData(){
        //        使用外部存储将序列化后的对象存储在根目录下的user_info下
        val file = File(Environment.getExternalStorageDirectory().absolutePath)
        try {
            if(!file.exists()){
                file.mkdir()
                Log.d("n","----------------------------------------------------------------------")
                Log.d("xiaz","文件夹创建成功")
            }
            val newFile = File(Environment.getExternalStorageDirectory().absolutePath,"/music_list_info.txt")
            if(!newFile.exists()){
                newFile.createNewFile()
                Log.d("n","----------------------------------------------------------------------")
                Log.d("xiaz","文件创建成功")
            }
            val fos= ObjectOutputStream(FileOutputStream(newFile))
            fos.writeObject(info_obj)
            fos.flush()
            fos.close()
            Log.d("n","----------------------------------------------------------------------")
            Log.d("xiaz","已保存对象")
        }catch (e:Exception){
            e.printStackTrace()
        }

    }


    private fun loadData(): Info? {
        return try {
            val file = File(Environment.getExternalStorageDirectory().absolutePath,"/music_list_info.txt")
            val fos= ObjectInputStream(FileInputStream(file))
            val obj=fos.readObject() as Info
            fos.close()
            Log.d("n","----------------------------------------------------------------------")
            Log.d("xiazai","已下载对象")
            obj
        }catch (e:Exception){
            e.printStackTrace()
            null
        }
    }

//    实现适配器中的点击事件方法
    override fun onItemClick(view: View?, position: Int) {
        val intent=Intent(this,MusicPlaying::class.java)
        val clickItem= musicList[position+5]
        music_num=sub((clickItem.num).toInt(),5)
        current= music_num+3
        startActivity(intent)
        Log.d("str","--------------------------------------------------")
        Log.d("name","您点击了第$current"+"首歌")

    }

    override fun onItemLongClick(view: View?, position: Int) {
    }

    private fun sub(a:Int, b:Int):Int{
        return a-b
    }

    companion object {
        private const val TAG = "MusicPlayList"
    }

}